#include <iostream>
#include <thread>
#include <mutex>
#include <condition_variable>

class Semaphore {
public:
    Semaphore(int count = 0) : count(count) {}

    void wait() {
        std::unique_lock<std::mutex> lock(mtx);
        cv.wait(lock, [this]() { return count > 0; });
        count--;
    }

    void signal() {
        std::unique_lock<std::mutex> lock(mtx);
        count++;
        cv.notify_one();
    }

private:
    std::mutex mtx;
    std::condition_variable cv;
    int count;
};

std::mutex mtx;
Semaphore emptySlots(10); // 初始化空闲槽位信号量为 10
Semaphore fullSlots(0);   // 初始化满槽位信号量为 0

void Tproduce() {
    emptySlots.wait();  // 等待空闲槽位

    {
        std::lock_guard<std::mutex> lock(mtx);
        std::cout << "(";
    }

    fullSlots.signal(); // 生产完毕，增加满槽位
}

void Tconsume() {
    fullSlots.wait();  // 等待满槽位

    {
        std::lock_guard<std::mutex> lock(mtx);
        std::cout << ")";
    }

    emptySlots.signal(); // 消费完毕，增加空闲槽位
}

int main() {
    std::thread producers[50], consumers[50];

    for (int i = 0; i < 50; i++) {
        producers[i] = std::thread(Tproduce);
    }

    for (int i = 0; i < 50; i++) {
        consumers[i] = std::thread(Tconsume);
    }

    for (int i = 0; i < 50; i++) {
        producers[i].join();
        consumers[i].join();
    }

    return 0;
}
